package com.provider.service.impl;

import java.util.Arrays;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

/**
 * DubboFilter
 *
 * @author H
 * @version 1.0
 * @date 2024-05-27 10:33
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class DubboFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = invoker.invoke(invocation);
        logInfo(invocation, result);
        return result;
    }

    private static void logInfo(Invocation invocation, Result result) {
        String interfaceName = invocation.getInvoker().getInterface().toString();
        String methodName = invocation.getMethodName();
        String requestType = Arrays.stream(invocation.getArguments()).map(t -> t.getClass().getName()).collect(Collectors.joining(","));
        String request = Arrays.stream(invocation.getArguments()).map(t -> t.toString()).collect(Collectors.joining(","));
        String targetServiceName = invocation.getTargetServiceUniqueName();
        Object response = result.getValue();
        String responseType = response.getClass().getName();

        log.info("Dubbo log|<|>|{}#{}({}):{}|<|>|{}|<|>|{}", interfaceName, methodName, requestType, responseType, request, response);
    }

}
